/****************************************************
          File Name:sem_timedwait.c
          Author: Abby Cin
          Mail: abbytsing@gmail.com
          Created Time: Sat 20 Sep 2014 07:30:30 PM CST
*****************************************************/
#include"posix_ipc.h"
#include<time.h>            /* clock_gettime */

int main(int argc,char *argv[])
{
    Usage(argc,"/sem",argv[0],argv[1]);

    sem_t *sem;
    sem=sem_open(argv[1],0);
    if(sem==SEM_FAILED)
        err("sem_open");

    struct timespec timeout;
    if(clock_gettime(CLOCK_REALTIME,&timeout)==-1)
        err("get current time");
    timeout.tv_sec+=5;           /* manual set timeout for second */
    timeout.tv_nsec=0;          /* manual set timeout for nanosecond */

    if(sem_timedwait(sem,&timeout)==-1)
    {
        if(errno==ETIMEDOUT)
        {
            printf("timedwait works\n");
            exit(EXIT_FAILURE);
        }
        else
            err("sem_timedwait");
    }

    printf("semaphore -1\n");
    exit(EXIT_SUCCESS);
}
